# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from common.helper import Helper
import requests
from urllib.parse import  urlencode
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安e家保2018"

    def genProductInfo(self):
        plan = {
            # 年龄段
            "year":["0-5","6-10","16-20","21-25","26-30","31-35","36-40","41-45","46-50","51-55","56-60"],
            # 有无社保
            "socialSec":["Y","N"],
            #保额
            "money":["400000","1000000","2000000","6000000","10000000"],
            #保障期限
            "expire":["1年"],
            #交费方式
            "payType":["年交"]
        }
        for v in product( plan["year"],plan["socialSec"],plan["money"],plan["expire"],plan["payType"]):
            data = Helper.formatProductInfo( plan ,v )
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( **data ))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format( **data ) )


    #执行爬虫
    def requestJson(self,dt=None):
        age = str(int(dt["year"].split("-")[0]) + 1)
        if dt["money"] == "400000":
            scheme = "01"
        elif dt["money"] == "1000000":
            scheme = "02"
        elif dt["money"] == "2000000":
            scheme = "03"
        elif dt["money"] == "6000000":
            scheme = "04"
        else:
            scheme = "05"
        data = {
            "personAge": age,
            "isShareAmount": "N",
            "schemeCode": scheme,
            "socialSecurity": dt["socialSec"],
            "gender": "F",
            "source_code": "PAH",
            "channel_code": "ejb2018",
            "post_id": "B7",
        }
        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200:
            price = Helper.decimalParse( r.json()["p_discount_premium"] )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)
